package io.adrainty.bolee.framework.commons.utils;

import cn.hutool.core.date.DatePattern;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import io.adrainty.bolee.framework.commons.basic.IEnum;
import io.adrainty.bolee.framework.commons.exception.CoreException;
import io.adrainty.bolee.framework.commons.serializer.EnumDeserializerFactory;
import io.adrainty.bolee.framework.commons.serializer.EnumSerializer;
import io.adrainty.bolee.framework.commons.serializer.SafeToStringSerializer;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.TimeZone;

/**
 * Json工具类
 * @author adrainty
 * @version v1.0.0
 * @since 2024/5/15 18:22
 */
@Slf4j
@SuppressWarnings("unused")
public class JsonUtil {

    private JsonUtil() {
    }

    private static final ObjectMapper MAPPER = new ObjectMapper();

    static {
        MAPPER.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        MAPPER.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        MAPPER.setTimeZone(TimeZone.getDefault());

        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DatePattern.NORM_DATETIME_FORMAT.getDateTimeFormatter()));
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DatePattern.NORM_DATE_FORMAT.getDateTimeFormatter()));
        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DatePattern.NORM_TIME_FORMAT.getDateTimeFormatter()));

        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DatePattern.NORM_DATETIME_FORMAT.getDateTimeFormatter()));
        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DatePattern.NORM_DATE_FORMAT.getDateTimeFormatter()));
        javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DatePattern.NORM_TIME_FORMAT.getDateTimeFormatter()));

        MAPPER.registerModule(javaTimeModule);

        SafeToStringSerializer stringSerializer = new SafeToStringSerializer();
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, stringSerializer);
        simpleModule.addSerializer(Long.TYPE, stringSerializer);

        simpleModule.addSerializer(IEnum.class, new EnumSerializer());
        simpleModule.setDeserializerModifier(new BeanDeserializerModifier() {
            @Override
            @SuppressWarnings("unchecked")
            public JsonDeserializer<IEnum> modifyEnumDeserializer(DeserializationConfig config,
                                                                  JavaType type,
                                                                  BeanDescription beanDesc,
                                                                  JsonDeserializer<?> deserializer) {
                // 只为实现了 IEnum 接口的枚举添加处理器
                if (IEnum.class.isAssignableFrom(type.getRawClass())) {
                    return EnumDeserializerFactory.getDeserializer(type);
                }
                return (JsonDeserializer<IEnum>) super.modifyEnumDeserializer(config, type, beanDesc, deserializer);
            }
        });

        MAPPER.registerModule(simpleModule);
    }

    public static ObjectMapper getMapper() {
        return MAPPER;
    }

    public static String toJson(Object obj) {
        try {
            return MAPPER.writeValueAsString(obj);
        } catch (Exception e) {
            throw new CoreException(e);
        }
    }

    public static <T> T fromJson(String json, Class<T> clazz) {
        try {
            return MAPPER.readValue(json, clazz);
        } catch (Exception e) {
            throw new CoreException(e);
        }
    }

    public static <T> T fromJson(String json, TypeReference<T> reference) {
        try {
            return MAPPER.readValue(json, reference);
        } catch (Exception e) {
            throw new CoreException(e);
        }
    }

}
